/**
 * 
 */
package com.ibuonline.search.solr.extend.mongo;

import java.util.Map;

import com.ibuonline.search.solr.support.MongoFactoryBean;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

/**
 * @author Liuye
 * 
 */
public abstract class BaseMongoDao {
	private Mongo mongo;
	private DB db;
	public static final String MONGO_ID_NAME = "_id";

	public void save(Map<String, Object> obj) {
		if (obj != null && !obj.isEmpty()) {
			// for (Map.Entry<String, Object> entry : obj.entrySet()) {
			// dbObj.pu(entry);
			// }
			DBObject q = new BasicDBObject();
			q.put(MONGO_ID_NAME, obj.get(MONGO_ID_NAME));
			DBObject dbObj = getDbCollection().findOne(q);
			if (dbObj == null) {// insert
				dbObj = new BasicDBObject();
				dbObj.putAll(obj);
				getDbCollection().save(dbObj);
			} else {// update
				dbObj.putAll(obj);
				getDbCollection().update(q, dbObj);
			}
		}
	}

	public boolean isExitst(String id) {
		DBObject q = new BasicDBObject();
		q.put("_id", id);
		return getDbCollection().findOne(q) != null;
	}

	public void delete(String id) {
		DBObject q = new BasicDBObject();
		q.put("_id", id);
		getDbCollection().remove(q);
	}

	public DBCollection getDbCollection() {
		return db.getCollection(getCollectionName());
	}

	/**
	 * @param mongoFactoryBean
	 *            the mongoFactoryBean to set
	 */
	public void setMongoFactoryBean(MongoFactoryBean mongoFactoryBean) {
		this.mongo = mongoFactoryBean.getMongo();
		this.db = mongo.getDB(mongoFactoryBean.getDatabase());
	}

	abstract String getCollectionName();

}
